<?php

class Controller_Users extends Controller_Template
{
    public function action_login()
    {
        $view = View::forge('users/login');
        $form = Form::forge('login');
        $auth = Auth::instance();
        $form->add('username', 'Username:');
        $form->add('password', 'Password:', array('type' => 'password'));
        $form->add('submit', ' ', array('type' => 'submit', 'value' => 'Login'));
        if (Input::post())
        {
            if ($auth->login(Input::post('username'), Input::post('password')))
            {       
               // Fuel\Core\Debug::dump($auth->get('id'));die();
                //Sau khi kiem tra login phai tao session(no chi tu dong tao session khi creat thoi.
                    $session=Session::instance();
                    Session::set('userid', $auth->get('id'));
                   // Fuel\Core\Debug::dump($session);die();
                //Debug::dump($auth->username);die();
                // $this->template->errors='ﾄ斉ハg nh蘯ｭp thﾃ�h cﾃｴng';  //ﾄ黛ｻ�nhﾆｰ th蘯ｿ nﾃ� trang sau ko hi盻㌻...
                Session::set_flash('message', 'Successfully logged in! Welcome ' . $auth->get('username')); //ﾄ黛ｻ�flash nhﾆｰ th蘯ｿ nﾃ� thﾃｬ 盻�trang sau s蘯ｽ ok..
                Response::redirect('users/index');
            } else
            {
                Session::set_flash('message', 'Username or password incorrect.');
            }
        }
        $form->repopulate();//Nﾃｳ s蘯ｽ gi盻ｯ l蘯｡i cﾃ｡c trﾆｰ盻拵g n蘯ｿu ﾄ惰ハg nh蘯ｭp sai.
        $view->set('form', $form, false);
        $this->template->title = 'User &raquo; Login';
        $this->template->content = $view;
    }

    public function action_logout()
    {
        $auth = Auth::instance();
        $auth->logout();
        Session::destroy();
        Session::set_flash('success', 'Logged out.');
        Response::redirect('users/login');
    }

    public function action_register()
    {   
        $view = View::forge('users/register');
        if (Input::method() == 'POST')
        {
            //$view->message="vao post";
            //t蘯｡o cﾃ｡c ﾄ訴盻「 ki盻㌻
            $val = Validation::forge();
            $val = Model_User::get_validation_register($val);
            //ki盻ノ tra cﾃ｡c ﾄ訴盻「 ki盻㌻ n蘯ｿu ok thﾃｬ t蘯｡o user m盻嬖 vﾃ�t蘯｡o session,ko thﾃｬ show l盻擁.
            //sau khi xong thﾃｬ chuy盻ハ ﾄ黛ｺｿn trang index.
            if ($val->run())
            {   
                //th盻ｱc hi盻㌻ t蘯｡o user v盻嬖 auth hash m蘯ｭt kh蘯ｩu,n蘯ｿu t蘯｡o ﾄ柁ｰ盻｣c tr蘯｣ v盻�id..
                $auth = Auth::instance();
                                                            // $session = Session::instance(); // ko c蘯ｧn kh盻殃 t蘯｡o session ,auth s蘯ｽ t盻ｱ ﾄ黛ｻ冢g gﾃ｡n session.
                if ($userid = $auth->create_user($val->validated('username'), $val->validated('password'), $val->validated('email')))
                {
                                                            //$a=Session::read(); //2 dﾃｲng nﾃ� ch盻ｩng minh lﾃ�ﾄ妥｣ t盻渡 t蘯｡i session. session read l蘯･y ﾄ黛ｻ訴 tﾆｰ盻｣ng session,session 盻�ﾄ妥｢y lﾃ�key lﾃ�userid.
                                                            //Fuel\Core\Debug::dump($a);die();
                                                            //Session::set('userid', $userid);
                                                            //Debug::dump($session);die();
                    $this->action_sendEmailConfirm(Session::get('userid'));
                    $this->template->set('errors', 'Thành công!');    
                } else
                {
                    //Session::set_flash('fail', 'Fail creat');     
                    $this->template->set('errors', $val->show_errors());
                }
//                 
            } else
            {
                $this->template->set('errors', $val->show_errors(),false);
            }
        }
        $this->template->title = 'User &raquo; Register';
        $this->template->set('content', $view, false); //false will tell fuel not to convert the html tags to safe string
    }
    public function action_index()
    {   
        //get session id and find user by that id.
        $user_id = Session::get('userid');
                                        // Fuel\Core\Debug::dump($user_id);die();
                                        //$Model_User = new Model_User();//ko cﾃ｢n kh盻殃 t蘯｡o v蘯ｫn ch蘯｡y t盻奏.
        $user = Model_User::find($user_id);  // nﾃｳ s蘯ｽ l蘯･y t蘯･t c蘯｣ cﾃ｡c trﾆｰ盻拵g ph盻･ thu盻冂 vﾃ� nh盻ｯng cﾃ｡i khai bﾃ｡o trong propertires!
                                        //        Fuel\Core\Debug::dump($user);die(); 
        $view = View::forge('users/index');
        $view->user=$user;
        $this->template->title = 'Index user page';
        $this->template->set('content', $view, false); //false will tell fuel not to convert the html tags to safe string
    }
    public function action_edit_account()
    {
        $id = Session::get('userid');
        if (Input::method() == 'POST')
        {
            // user must put correct password to edit account
            $pw = Auth::instance()->hash_password(Input::post('password'));
            $data=Model_User::query()->where('id', $id)->where('password', $pw);
            if ($data->count()==0)
            {
                Session::set_flash('message', 'Your password is incorrect. Please, try again.'); //ﾄ黛ｻ�flash nhﾆｰ th蘯ｿ nﾃ� thﾃｬ 盻�trang sau s蘯ｽ ok..
                Response::redirect('users/edit_account');
            }
            //edit account
            $val = Validation::forge();
            $val = Model_User::get_validation_edit_account($val); //trong nay van thieu dk kiem tra trung email hay username vs ng khac
            if ($val->run())
            {   
                $user = Model_User::find($id);;
                $user->set(array(
                    'username' => Input::post('username'),
                    'email' => Input::post('email'),
                ));
                $user->save();
                Session::set_flash('message', 'The informations has been changed.');
                Response::redirect('users/index');
            }
            else
            {
                Session::set_flash('message', $val->show_errors());
            }
        } else
        {       // if haven't click submit yet..get data and send to view to assign to input form ..
                $view = View::forge('users/edit_account');
                $user = Model_User::find($id);
                $view->user = $user;
                $this->template->title = 'edit account';
                $this->template->set('content', $view, false); //false will tell fuel not to convert the html tags to safe string
        }
    }
    
    public function action_edit_password()
    {
        $id = Session::get('userid');
        if (Input::method() == 'POST')
        {
            $val = Validation::forge();
            $val = Model_User::get_validation_edit_password($val); //trong nay van thieu dk kiem tra trung email hay username vs ng khac
            // user must put correct password to change password
            $pw = Auth::instance()->hash_password(Input::post('oldpassword'));
            $data=Model_User::query()->where('id', $id)->where('password', $pw);
//            Fuel\Core\Debug::dump($data);die();       
            if ($data->count()==0)
            {
                Session::set_flash('message', 'Your password is incorrect. Please, try again.'); //ﾄ黛ｻ�flash nhﾆｰ th蘯ｿ nﾃ� thﾃｬ 盻�trang sau s蘯ｽ ok..
                Response::redirect('users/edit_password');
            }
            if ($val->run())
            {   
                //update data
                $pw = Auth::instance()->hash_password(Input::post('password'));
                $user = Model_User::find($id);
                $user->set(array(
                    'password' => $pw,
                ));
                $user->save();
                Session::set_flash('message', 'The Password has been changed.');
                Response::redirect('users/index');
            }
            else
            {
                Session::set_flash('message', $val->show_errors());
                Response::redirect('users/edit_password');
            }
        } 
        else 
        {
            $view = View::forge('users/edit_password');
            $this->template->title = 'edit password';
            $this->template->set('content', $view, false); //false will tell fuel not to convert the html tags to safe string 
        }
        
    }
    
    public function action_sendEmailConfirm($id)
    {
        $data=  Model_User::find($id);
        $email_data['id']=$id;
        $email_data['email']=$data->email;
        $email_data['name']=$data->username;
        $email= \Email::forge();
        $email->subject('Email confirmation');
        $email->html_body(\View::forge('email/addemail', $email_data));
        $email->from('khoaitayran201291@gmail.com');
        $email->to('khoaitayran201291@gmail.com');
        
        //
//        $view=  View::forge('email/addemail');
//        $view->id=$id;
//        $view->email=$data->email;
//        $view->name=$data->username;
//        $this->template->set('content', $view, false); 
        
        try
        {
        $email->send();
        
        } catch (\EmailValidationFailedException $e)
        {
            Debug::dump($e)  ;
        } catch (\EmailSendingFailedException $e)
        {
           Debug::dump($e)  ;
        }
    }
    
    public function action_check_active($pass)
    {
        //decode params
        $pass = base64_decode($pass);
        $pass = explode('-', $pass);
        $id = $pass[0];
        $username = $pass[1];
        //authenticate link active
//        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id, 'User.username' => $username));
//        $a = $this->User->find('first', $options);
        $a=  Model_User::query()->where('id',$id)->where('username',$username)->get_one();
        //if have already actived or invalid active params ,return to login page...
        if ($a->status== 1 || $a == null)
        {   
            Session::set_flash('message','Can not active anymore !');
            Response::redirect('users/index');
            
        }
        //start active
        $user= Model_User::find($id) ;
        $user->status = 1;

        if ($user->save())
        {
            Session::set_flash('message', 'your account has been actived!');
            //creat session to redirect to home page
            Session::set('userid', $id);
            Response::redirect('users/index');
            {
            Session::set_flash('message', 'eror');
            }
        }





    }
}

/* code tham khao */
//            $auth = Auth::instance();
//            $view = View::forge('users/register');
//            $form = Fieldset::forge('register');//create the register fieldset
//            Model_User::register($form);//pass this form to model.
        //creat register form an add rules to it.
//        $form = Fieldset::forge();
//        $form->add('username', 'Username:')->add_rule('required');
//        $form->add('password', 'Choose Password:', array('type'=>'password'))->add_rule('required');
//        $form->add('password2', 'Re-type Password:', array('type' => 'password'))->add_rule('required');
//        $form->add('email', 'E-mail:')->add_rule('required')->add_rule('valid_email');
//        $form->add('submit', ' ', array('type'=>'submit', 'value' => 'Register'));
//        if (Input::post())
//        {
//            $form->repopulate();
//            $result = Model_User::validate_registration($form, $auth);
//            if ($result['e_found'])
//            {
//                $view->set('errors', $result['errors'], false);
//            } else
//            {
//                Session::set_flash('success', 'User created.');
//                Response::redirect('./');
//            }
//        }